package com.kaka.starter.token.service;

import com.kaka.starter.token.dto.TokenDTO;
import com.kaka.starter.token.dto.TokenParamDTO;
import com.kaka.starter.token.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author kaka
 * @Date 2020-07-03
 */
@Component
public class TokenService {

    @Autowired
    private TokenParamDTO tokenParamDTO;
    @Cacheable(value = "userToken", key = "#id")
    public TokenDTO get(Integer id) {
        return null;
    }

    @Cacheable(value = "userToken", key = "#id")
    public TokenDTO set(Integer id, Map tokenMap) {

        String token = JWTUtils.createJWT(tokenMap,
                tokenParamDTO.getAuthSecret(), 60 * 60 * 24 * 60);
        return new TokenDTO()
                .setId(id)
                .setToken(token)
                .setExpires(60 * 60 * 24 * 60);
    }

    @CacheEvict(value = "userToken", key = "#id")
    public void destory(Integer id) {
    }

    //@CacheEvict(value = "tokenCache", key = "#token")
    //public void destroyUserId(String token) {
    //}
    //
    @Cacheable(value = "tokenCache", key = "#token")
    public String getUserId(String token, String key) {
        if (token == null || key == null) {
            throw new NullPointerException("参数传递不正确");
        }
        JWTUtils.JWTResult jwtResult = JWTUtils.parse(token, tokenParamDTO.getAuthSecret());
        JWTUtils.addJWTResut2LocalCache(jwtResult);
        return (String) jwtResult.get(key).get();
    }

}
